package com.smart_campus.sys.service.impl;

import com.smart_campus.sys.common.MD5Utils;
import com.smart_campus.sys.common.ResultObj;
import com.smart_campus.sys.common.UserEntity;
import com.smart_campus.sys.domain.UserInfo;
import com.smart_campus.sys.mapper.UserInfoMapper;
import com.smart_campus.sys.service.UserInfoService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.smart_campus.sys.common.*;
import com.smart_campus.sys.service.UserService;
import com.smart_campus.sys.vo.RoleVo;
import com.smart_campus.sys.vo.UserANDRoleANDDeptVO;
import com.smart_campus.sys.vo.UserAndUserInfoVo;
import com.smart_campus.sys.vo.UserVo;
import com.smart_campus.sys.common.StringUtils;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.smart_campus.sys.mapper.UserMapper;
import com.smart_campus.sys.domain.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
*@Author:Omega
*@Date:2020/6/6 15:14
*/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private UserInfoServiceImpl userInfoService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 登录时查询登录名的所有信息
     * @param loginname
     * @return
     */
    @Override
    public User querUserByLoginName(String loginname) {
        if (StringUtils.isBlank(loginname)){
            return null;
        }
        User user = new User();
        user = userMapper.querUserByLoginName(loginname);
        return user;
    }

    /**
     * 判断手机号是否被注册
     * @param phone
     * @return
     */
    @Override
    public Boolean queryUserByPhone(String phone) {
        return StringUtils.isNullOrEmpty(userMapper.querUserByPhone(phone));
    }

    /**手机注册会走这个方法
     * @param user
     * @return
     */
    @Override
    public ResultObj insertUser(User user) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
        user.setLoginname(sdf.format(new Date()));
        //如果手机号不为空则进入用户名注册
        if (!StringUtils.isBlank(user.getPhone())) {
            //该手机号存在则添加失败
            if (!queryUserByPhone(user.getPhone())){
                return new ResultObj(-1,"该手机号已被注册！");
            }
            user.setUsername(UserEntity.USER_NAME);
            user.setPassword(MD5Utils.md5(UserEntity.USER_PASSWORD));
            user.setOrdernum(userMapper.querMax()+1);
            user.setRole(UserEntity.USER_ROLE);
            System.out.println("charu"+user.getUsername());
            //通过主键回填把用户id插入用户详情表
            try {
                userMapper.insertUser(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(user.getUserId());
            System.out.println("charu"+user.getUserId());
            userInfo.setInfoordernum(userInfoService.querMax()+1);
            userInfo.setFilt(UserEntity.USER_FILT);
            userInfoService.insert(userInfo);
            return new ResultObj(200, user.getLoginname());
        }
        return ResultObj.ADD_ERROR;
    }

    /**
     * 添加员工
     * @param user
     * @return
     */
    @Override
    public ResultObj insertstaff(User user) {

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
            user.setLoginname(sdf.format(new Date()));
            user.setPassword(MD5Utils.md5("123456"));
            user.setRole("1");
            user.setOrdernum(userMapper.querMax()+1);
            userMapper.insertstaff(user);
            UserInfo userInfo=new UserInfo();
            userInfo.setUserId(user.getUserId());
            userInfo.setInfoordernum(userInfoService.querMax()+1);
            userInfoService.insert(userInfo);
            return new ResultObj(200,user.getLoginname());
        } catch (Exception e) {
            return ResultObj.ADD_SUCCESS;
        }
    }

    /**身份证会走这一条
     * 用户注册升级版
     * @param user
     * @param userInfo
     * @return
     */
    @Override
    public ResultObj insertUserAndINfo(User user, UserInfo userInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
        user.setLoginname(sdf.format(new Date()));
        user.setOrdernum(userMapper.querMax()+1);
        //如果手机号为空则进入用户名注册
        if (StringUtils.isBlank(user.getPhone())) {
            //密码和用户名为空则添加失败
            if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
                return new ResultObj(-1, "添加失败");
            }
            user.setPassword(MD5Utils.md5(user.getPassword()));
            //通过主键回填把用户id插入用户详情表
            try {
                userMapper.insertUser(user);
            } catch (Exception e) {
                //给用户详情表加值
                userInfo.setIdentity(userInfo.getIdentity());
                userInfo.setUserId(user.getUserId());
                userInfo.setCreateTime(new Date());
                userInfo.setUpdateTime(new Date());
                userInfo.setFilt(UserEntity.USER_FILT);
                userInfo.setVersion(1);
                userInfo.setInfoordernum(userInfoService.querMax()+1);
                userInfoService.insert(userInfo);
            }
            return new ResultObj(200, user.getLoginname());
        }
        //该手机号存在则添加失败
        if (!queryUserByPhone(user.getPhone())){
            return new ResultObj(-1,"该手机号已被注册！");
        }
        user.setUsername(UserEntity.USER_NAME);
        user.setPassword(MD5Utils.md5(UserEntity.USER_PASSWORD));
        userMapper.insertUser(user);
        return new ResultObj(200,user.getLoginname());
    }

    /**
     * 实名找回密码
     * @param username
     * @param loginname
     * @param password
     * @param identity
     * @return
     */
    @Override
    public ResultObj autonymRetrieve(String username, String loginname, String password, String identity) {
        Map map=userMapper.selectUserVerify(username,loginname,identity);
        try {
            if (map.get("username")!=null){
                userMapper.updateUserPwd((Integer) map.get("user_id"),MD5Utils.md5(password));
                return ResultObj.RETRIEVE_TRUE;
            }
        } catch (Exception ignored){
            ignored.printStackTrace();
        }

        return ResultObj.RETRIEVE_FALSE;
    }

    /**
     *
     * @param userVo
     * @return List<User>
     */
    @Override
    public DataGridView selectUser(UserVo userVo) {
        Page<Object> page= PageHelper.startPage(userVo.getPage(), userVo.getLimit());//分页数据格式
        List<Map> roleVos= userMapper.selectUser(userVo);//返回的全部数据
        return new DataGridView(page.getTotal(),roleVos);
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUserinfo(id);
        userMapper.deleteUser(id);
        userMapper.deleteUserRole(id);
    }


    /**
     * 删除对应id用户角色相关表的信息
     * @param uid
     * @return int
     */
    @Override
    public int deleteUserRole(Integer uid) {
        return userMapper.deleteUserRole(uid);
    }

    /**
     * 添加对应id用户角色相关表的信息
     * @param uid
     * @param rid
     * @return int
     */
    @Override
    public int insertUserRole(Integer uid, Integer rid) {

        return userMapper.insertUserRole(uid,rid);
    }

    @Override
    public void UserANDRoleANDDeptVOUPATE(UserANDRoleANDDeptVO userANDRoleANDDeptVO) {
            userANDRoleANDDeptVO.setUpdate_time(new Date());
            userMapper.updateUser(userANDRoleANDDeptVO);
            userMapper.updateinfoUser(userANDRoleANDDeptVO);
    }

    @Override
    public int updateAvailable(Integer id, Integer available) {
        return userMapper.updateAvailable(id,available);
    }

    @Override
    public int updateUserPwd(Integer id) {
        return userMapper.updateUserPwd(id,MD5Utils.md5("123456"));
    }

    @Override
    public DataGridView getCurrentUser() {
        Subject subject= SecurityUtils.getSubject();
        ActiveUser activeUser= (ActiveUser) subject.getPrincipal();
        User user = activeUser.getUser();
        return new DataGridView(userMapper.getCurrentUser(user.getUserId()));
    }

    /**
     * 头像上传
     * @param userInfo
     * @return
     */
    @Override
    public int updateFilt(UserInfo userInfo) {
        System.out.println();
        return userMapper.updateFilt(userInfo);
    }

    /**
     * 通过手机号查询后更改密码
     * @param user
     * @return
     */
    @Override
    public ResultObj phoneUpdatePassword(User user) {
        User userPass=userMapper.querUserByPhone(user.getPhone());
        userPass.setPassword(MD5Utils.md5(user.getPassword()));
        try {
            System.out.println("密码"+userPass.getPassword());
            userMapper.updatePhonePassword(userPass);
            return ResultObj.RETRIEVE_TRUE;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.RETRIEVE_FALSE;
        }
    }

    @Override
    public List<Map> queryAllUserForList() {

        return this.userMapper.queryAllUserForList();
    }


    @Override
    public DataGridView getUser(Integer id) {
        return new DataGridView(userMapper.getUser(id));
    }

    @Override
    public UserAndUserInfoVo getUserPhoneIdentity() {
        Subject subject= SecurityUtils.getSubject();
        ActiveUser activeUser= (ActiveUser) subject.getPrincipal();
        User user = activeUser.getUser();
        UserAndUserInfoVo userInfoVo = new UserAndUserInfoVo();
        userInfoVo.setUser(userMapper.querUserByLoginName(user.getLoginname()));
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getUserId());
        userInfoVo.setUserInfo(userInfoMapper.selectByUserInfo(userInfo));
        return userInfoVo;
    }
}
